﻿using System.Collections;
using System.Diagnostics;
using ModuleBase;
using ModuleBase.googoltech.GTS;
using Newtonsoft.Json;
using Prism.Ioc;

namespace FilmTheMold
{
    public class FilmTheMold : ModuleBase.ModuleBase
    {
        private IAxisCardService _axisCardService;
        private ModuleStateService _moduleStateService;
        bool outputs = false;
        private IContainerProvider containerProvider;
        Stopwatch sw = new Stopwatch();
        int handIndex = 0;


        private object _parameter1;
        public object Parameter1
        {
            get => _parameter1;
            set
            {
                if (_parameter1 != value)
                {
                    _parameter1 = value;
                    OnPropertyChanged(nameof(Parameter1));
                }
            }
        }
        private object _parameter2;
        public object Parameter2
        {
            get => _parameter2;
            set
            {
                if (_parameter2 != value)
                {
                    _parameter2 = value;
                    OnPropertyChanged(nameof(Parameter2));
                }
            }
        }
        private double _parameter3;
        public double Parameter3
        {
            get => _parameter3;
            set
            {
                if (_parameter3 != value)
                {
                    _parameter3 = value;
                    OnPropertyChanged(nameof(Parameter3));
                }
            }
        }
        public override Dictionary<string, object> GetProperties()
        {
            return new Dictionary<string, object>
            {
                { "位置", Parameter1 },
                { "Z轴", Parameter2 },
                { "Z速度", Parameter3 },
            };
        }

        public override Dictionary<string, List<object>> PropertyOptions { get; } = new Dictionary<string, List<object>>
        {
            { "位置", new List<object> {  "左","右" } },
            { "Z轴", new List<object> {  1,2,3,4,5,6,7,8 } }
        };
        public FilmTheMold(IAxisCardService axisCardService, ModuleStateService moduleStateService)
        {
            Name = "贴膜";
            _axisCardService = axisCardService;
            _moduleStateService = moduleStateService;
            _moduleStateService.RegisterModule(Id);
            DisplayNameToPropertyNameMap = new Dictionary<string, string>
            {
                { "位置", nameof(Parameter1) },
                { "Z轴", nameof(Parameter2) },
                { "Z速度", nameof(Parameter3) },
            };
        }

        public override bool Execute()
        {
            Status = ModuleStatus.Executing; // 设置状态为执行中
            int exoIndex = 7;
            AxisParm _axisZ = GetAxisByNumber((int)Parameter2);
            var moldPositionZ = 0.0;
            using var mdb = containerProvider.Resolve<MDbContext>();
            if (Parameter1.ToString() == "左")
            {
                var _mParam = mdb.MParams.FirstOrDefault(x => x.Name == "MoldPosition" && x.Hand == 0);
                if (_mParam != null)
                {
                    var _point = JsonConvert.DeserializeObject<MPoint>(_mParam.Value);
                    moldPositionZ = _point.Z;
                }
                exoIndex = 6;
            }
            else
            {
                var _mParam = mdb.MParams.FirstOrDefault(x => x.Name == "MoldPosition" && x.Hand == 1);
                if (_mParam != null)
                {
                    var _point = JsonConvert.DeserializeObject<MPoint>(_mParam.Value);
                    moldPositionZ = _point.Z;
                }
                exoIndex = 8;
                handIndex = 1;
            }
            try
            {
                int stepNum = 0;
                while (true)
                {
                    switch (stepNum)
                    {
                        case 0:
                            if (!_moduleStateService.IsStopped)
                            {
                                GTSCard.ServoOn(_axisZ);

                                stepNum = 1;
                            }
                            break;
                        case 1:
                            if (!_moduleStateService.IsStopped)
                            {
                                GTSCard.AxisPosSet(_axisZ, GTSCard.GetEnc(_axisZ));
                                stepNum = 2;
                            }
                            break;
                        case 2:
                            if (!_moduleStateService.IsStopped)
                            {
                                GTSCard.AxisPosMove(ref _axisZ, moldPositionZ, (double)Parameter3);
                                stepNum = 3;
                            }
                            break;
                        case 3: //Z轴运行到贴膜位
                            if (!_moduleStateService.IsStopped)
                            {
                                if (GTSCard.AxisPosMoveCheckDone(_axisZ))
                                {
                                    stepNum = 5;
                                }
                            }
                            else
                            {
                                GTSCard.AxisStop(_axisZ, 0);
                                stepNum = 3;
                            }
                            break;
                        case 5: //打开真空吹，等待0.5s
                            if (!_moduleStateService.IsStopped)
                            {
                                GTSCard.SetDo((short)_axisZ.CardNo, (short)exoIndex, 1);
                                sw.Start();
                                stepNum = 8;
                            }
                            break;
                        case 8:
                            if (!_moduleStateService.IsStopped)
                            {
                                if (sw.Elapsed.TotalSeconds > 0.5)
                                {
                                    sw.Stop();
                                    GTSCard.SetDo((short)_axisZ.CardNo, (short)exoIndex, 0);
                                    stepNum = 9;
                                }
                            }
                            break;
                        case 9:
                            outputs = true;
                            var _mParam = mdb.MParams.FirstOrDefault(x => x.Name == "IsWorking");
                            if (_mParam != null)
                            {
                                _mParam.Hand = handIndex == 0 ? 1 : 0;
                                mdb.SaveChanges();
                            }
                            return outputs;
                    }
                }
            }
            catch (Exception exp)
            {
                outputs = false;
            }
            return outputs;
        }

        public override async Task<bool> ExecuteAsync()
        {
            var result = await Task.Run(() => Execute());
            return result;
        }

        public override void Initialize()
        {

        }
        private AxisParm GetAxisByNumber(int axisNumber)
        {
            switch (axisNumber)
            {
                case 1: return _axisCardService.A1;
                case 2: return _axisCardService.A2;
                case 3: return _axisCardService.A3;
                case 4: return _axisCardService.A4;
                case 5: return _axisCardService.A5;
                case 6: return _axisCardService.A6;
                case 7: return _axisCardService.A7;
                case 8: return _axisCardService.A8;
                default: return _axisCardService.A1;
            }
        }
    }
}
